/**
 * Created by Anard on 2017/4/19.
 */
var userDao = require('../mysql/userDao.js');
var md5 = require('md5');
var net = require('net');
var variable = require('../../config/variable.js');
var toGate = require('../util/toGate.js');

var argv = process.argv.splice(2);
var socketPort = argv[0];

net.createServer(function (c) { // Connection监听器
    toGate.setLink(c);
    c.on("end", function () {
        console.log('连接断开')
    });
    c.on("error", function () {
        //console.error('连接错误')
    });
    c.on('data', function (message) {
        var obj = JSON.parse(message.toString());
        var data = obj.data;
        switch (obj.action) {
            case 'reg':
                var userModel = new userDao();
                userModel.inAccount(data.account, function (err, res) {
                    if (res != null) {
                        toGate.send(obj.uuid, 'error', {'code': 10011});
                        return false;
                    }
                    userModel.set('account', data.account);
                    userModel.set('password', md5(data.password));
                    userModel.save(function (err, res) {
                        if (res == null) {
                            toGate.send(obj.uuid, 'error', {'code': 10012});
                        } else {
                            toGate.send(obj.uuid, 'reg');
                        }
                    });
                });
                break;
            case 'login':
                var userModel = new userDao();
                userModel.inAccount(data.account, function (err, res) {
                    if (res == null) {
                        toGate.send(obj.uuid, 'error', {'code': 10001});
                        return false;
                    }
                    if (!userModel.checkPass(data.password)) {
                        toGate.send(obj.uuid, 'error', {'code': 10002});
                        return false;
                    }
                    var random = parseInt(100000 + (999999 - 100000) * (Math.random()));
                    var token = userModel.data.id + '&' + random;
                    userModel.set('token', md5(token));
                    userModel.save(function (err1, res1) {
                        if (res1 == null) {
                            toGate.send(obj.uuid, 'error', {'code': 10003});
                        } else {
                            toGate.send(obj.uuid, 'login', {'id': res.res.id, 'token': res.res.token});
                        }
                    });
                });
                break;
        }
    });
}).listen(socketPort, function () {
    // Listening监听器
    console.log("登陆服务器启动:" + socketPort);
});
